<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="main-header">
          <span>反馈看板</span>
          <el-button
            type="text"
            @click="toggleFullScreen"
            :icon="isFullScreen ? 'el-icon-close' : 'el-icon-full-screen'"
            size="small"
            title="全屏显示"
          ></el-button>
        </div>
      </template>
      
      <!-- 统一日期选择器 -->
      <div class="unified-date-filter" style="padding: 15px 0; border-bottom: 1px solid #ebeef5; margin-bottom: 15px;">
        <el-date-picker
          v-model="selectedDate"
          type="date"
          placeholder="选择日期"
          @change="handleUnifiedDateChange"
          size="small"
        ></el-date-picker>
      </div>
      
      <!-- 年段Tab切换 -->
      <div class="tab-container">
        <el-tabs
          v-model="activeSectionId"
          @tab-click="handleSectionChange"
          type="border-card"
        >
          <el-tab-pane
            v-for="section in sectionList"
            :key="section.id"
            :label="section.section_name"
            :name="section.id.toString()"
          >
            <div class="chart-container">
              <!-- 整体布局：两列 -->
              <div class="main-layout">
                <!-- 左侧列：包含教师统计、家长统计和下方两栏 -->
                <div class="left-column">
                  <!-- 上方两个图表 -->
                  <div class="top-charts">
                    <!-- 教师填报统计柱状图 -->
                    <el-card class="chart-card">
                      <template #header>
                        <div class="chart-header">
                          <span>教师填报统计</span>
                        </div>
                      </template>
                      <div ref="teacherReportChart" class="chart"></div>
                    </el-card>

                    <!-- 家长互动统计柱状图 -->
                    <el-card class="chart-card">
                      <template #header>
                        <div class="chart-header">
                          <span>家长互动统计</span>
                        </div>
                      </template>
                      <div ref="parentInteractionChart" class="chart"></div>
                    </el-card>

                    <!-- 反馈类型统计饼图 -->
                    <el-card class="chart-card">
                      <template #header>
                        <div class="chart-header">
                          <span>反馈类型统计</span>
                        </div>
                      </template>
                      <div ref="feedbackTypeChart" class="chart"></div>
                    </el-card>
                  </div>

                  <!-- 下方两栏布局 -->
                  <div class="bottom-sections">
                    <!-- 家长说 -->
                    <div class="parent-comments-section">
                      <el-card class="chart-card parent-comments-container">
                        <template #header>
                          <div class="chart-header">
                            <span>家长说</span>
                            <div class="filter-container">
                              <!-- 只保留班级选择器，日期已统一 -->
                              <el-select
                                v-model="parentCommentClass"
                                placeholder="选择班级"
                                @change="handleParentCommentClassChange"
                                size="small"
                              >
                                <el-option
                                  v-for="cls in classList"
                                  :key="cls.id"
                                  :label="cls.className"
                                  :value="cls.id"
                                ></el-option>
                              </el-select>
                            </div>
                          </div>
                        </template>
                        <div class="parent-comments-scroll-container">
                          <el-table
                            :data="flattenComments"
                            style="width: 100%"
                            size="small"
                          >
                            <el-table-column
                              prop="studentName"
                              label="学生姓名"
                              width="50"
                            ></el-table-column>
                            <el-table-column
                              prop="className"
                              label="班级"
                              width="50"
                            ></el-table-column>
                            <el-table-column
                              prop="time"
                              label="时间"
                              width="100"
                            ></el-table-column>
                            <el-table-column
                              prop="content"
                              label="留言内容"
                              show-overflow-tooltip
                            >
                              <template #default="scope">
                                <div class="comment-content-cell">
                                  {{ scope.row.content || "暂无留言" }}
                                </div>
                              </template>
                            </el-table-column>
                          </el-table>
                          <div
                            v-if="flattenComments.length === 0"
                            class="no-comments"
                          >
                            暂无家长留言
                          </div>
                        </div>
                      </el-card>
                    </div>

                    <!-- 幼儿个体动态 -->
                    <div class="student-indicators-section">
                      <el-card class="chart-card student-indicators-container">
                        <template #header>
                          <div class="chart-header">
                            <span>幼儿个体动态</span>
                            <div class="filter-container">
                              <!-- 只保留班级选择器，日期已统一 -->
                              <el-select
                                v-model="studentIndicatorClass"
                                placeholder="选择班级"
                                @change="handleStudentIndicatorClassChange"
                                size="small"
                              >
                                <el-option
                                  v-for="cls in classList"
                                  :key="cls.id"
                                  :label="cls.className"
                                  :value="cls.id"
                                ></el-option>
                              </el-select>
                            </div>
                          </div>
                        </template>
                        <div class="students-scroll-container">
                          <div
                            v-for="student in studentIndicatorsData"
                            :key="student.id"
                            class="student-indicator-card"
                          >
                            <div class="student-header">
                              <div
                                class="student-avatar"
                                :style="{
                                  backgroundColor: student.avatarColor,
                                }"
                              >
                                {{ student.name.charAt(0) }}
                              </div>
                              <div class="student-info">
                                <div class="student-name">
                                  {{ student.name }}
                                </div>
                                <div class="student-class">
                                  {{ student.className }}
                                </div>
                              </div>
                            </div>
                            <div
                              :id="`studentChart_${student.id}`"
                              class="student-chart"
                            ></div>
                          </div>
                        </div>
                      </el-card>
                    </div>
                  </div>
                </div>

                <!-- 右侧列：全段指标动态，占满整个高度 -->
                <div class="right-column">
                  <el-card class="chart-card right-chart">
                    <section-indicators-table 
                      :query-date="selectedDate"
                      :section-id="activeSectionId"
                      title="全段指标动态"
                    />
                  </el-card>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
  </div>
</template>

<script>
import api from "@/utils/api.js";
import * as echarts from "echarts";
import SectionIndicatorsTable from "@/components/dailyFeedback/SectionIndicatorsTable.vue";

export default {
  name: "dailyBoard",
  components: {
    SectionIndicatorsTable
  },
  data() {
    return {
      activeSectionId: "1", // 默认选中第一个年段
      sectionList: [],
      teacherReportChart: null, // 教师填报统计图表
      parentInteractionChart: null, // 家长互动统计图表
      completionRateChart: null,
      feedbackTypeChart: null,
      // 指标数据状态 - 现在由SectionIndicatorsTable组件管理
      // indicatorsData: [],
      // 家长说模块数据
      parentCommentsData: [],
      // 幼儿个体动态模块数据
      studentIndicatorsData: [],
      
      studentCharts: {},
      
      // 筛选条件
      selectedDate: new Date(), // 统一日期选择器值
      selectedClass: '', // 选中的班级
      classList: [], // 班级列表
      
      // 各模块的班级筛选条件（保留，日期筛选已统一）
      parentCommentClass: '',
      studentIndicatorClass: '',
      // 全屏状态标志
      isFullScreen: false,
    };
  },
  mounted() {
    this.initSection();
    
    // 添加全屏状态监听
    document.addEventListener('fullscreenchange', this.handleFullScreenChange);
    document.addEventListener('webkitfullscreenchange', this.handleFullScreenChange);
    document.addEventListener('mozfullscreenchange', this.handleFullScreenChange);
    document.addEventListener('MSFullscreenChange', this.handleFullScreenChange);
    
    // 添加窗口大小变化监听
    window.addEventListener('resize', this.resizeCharts);
    
    // 页面加载完成后立即尝试加载家长留言数据
    // 这是额外的保险，确保即使其他地方没有触发，数据也能加载
    setTimeout(() => {
      console.log('页面加载完成，尝试加载家长留言数据');
      this.loadParentCommentsData();
    }, 1000);
  },
  computed: {
    // 计算属性：扁平化的留言数据，用于表格显示
    flattenComments: function () {
      console.log('parentCommentsData状态:', this.parentCommentsData);
      
      let result = [];
      
      // 确保parentCommentsData是数组
      if (Array.isArray(this.parentCommentsData)) {
        this.parentCommentsData.forEach((student, index) => {
          console.log(`处理学生[${index}]:`, student);
          
          // 检查学生对象是否有效
          if (student && typeof student === 'object') {
            if (student.parentComments && Array.isArray(student.parentComments) && student.parentComments.length > 0) {
              student.parentComments.forEach((comment, commentIndex) => {
                console.log(`  处理留言[${commentIndex}]:`, comment);
                result.push({
                  studentName: student.name || '未知学生',
                  className: student.className || (this.classList.find(cls => cls.id === this.parentCommentClass)?.className || '未知班级'),
                  time: comment.time || new Date().toLocaleDateString(),
                  content: comment.content || "暂无留言",
                });
              });
            } else {
              // 有学生但没有留言，仍然显示该行
              result.push({
                studentName: student.name || '未知学生',
                className: student.className || (this.classList.find(cls => cls.id === this.parentCommentClass)?.className || '未知班级'),
                time: '',
                content: "暂无留言",
              });
            }
          }
        });
      }
      
      console.log('生成的flattenComments数据:', result);
      return result;
    },
  },
  beforeDestroy() {
    // 销毁图表实例
    if (this.teacherReportChart) {
      this.teacherReportChart.dispose();
    }
    if (this.parentInteractionChart) {
      this.parentInteractionChart.dispose();
    }
    if (this.completionRateChart) {
      this.completionRateChart.dispose();
    }
    if (this.feedbackTypeChart) {
      this.feedbackTypeChart.dispose();
    }
    // 销毁所有学生图表实例
    Object.values(this.studentCharts).forEach((chart) => {
      if (chart) {
        chart.dispose();
      }
    });
    
    // 移除全屏状态监听
    document.removeEventListener('fullscreenchange', this.handleFullScreenChange);
    document.removeEventListener('webkitfullscreenchange', this.handleFullScreenChange);
    document.removeEventListener('mozfullscreenchange', this.handleFullScreenChange);
    document.removeEventListener('MSFullscreenChange', this.handleFullScreenChange);
    
    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.resizeCharts);
    window.removeEventListener('resize', this.handleChartResize);
    
    // 确保退出全屏
    if (this.isFullScreen) {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      }
    }
  },
  methods: {
    // 初始化年段数据
    initSection() {
      this.$fetch(api.user_sectionindex, { p: 1 })
        .then((response) => {
          console.log(response,'年段数据');
          if (response.code === 0) {
            this.sectionList = response.list.data;
            if (this.sectionList.length > 0) {
              this.activeSectionId = this.sectionList[0].id.toString();
              this.loadClassList(); // 加载班级列表
              this.handleSectionChange();
            }
          } else {
            this.$message.error("获取年段数据失败");
          }
        })
        .catch((err) => {
          console.log(err);
          this.$message.error("获取年段数据失败");
        });
    },
    
    // 切换全屏状态
    toggleFullScreen() {
      const container = document.querySelector('.app-container');
      if (!container) return;

      if (!this.isFullScreen) {
        // 进入全屏
        if (container.requestFullscreen) {
          container.requestFullscreen();
        } else if (container.mozRequestFullScreen) {
          container.mozRequestFullScreen();
        } else if (container.webkitRequestFullscreen) {
          container.webkitRequestFullscreen();
        } else if (container.msRequestFullscreen) {
          container.msRequestFullscreen();
        }
      } else {
        // 退出全屏
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) {
          document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        }
      }
    },
    
    // 监听全屏状态变化
    handleFullScreenChange() {
      this.isFullScreen = !!(document.fullscreenElement ||
                           document.mozFullScreenElement ||
                           document.webkitFullscreenElement ||
                           document.msFullscreenElement);
    },
    
    // 加载班级列表 - 基于当前选中的年段
    loadClassList() {
      // 返回Promise以便外部可以使用then链式调用
      return this.$fetch(api.getClassListBySection, { sectionId: this.activeSectionId })
        .then((response) => {
          console.log(response, '班级数据');
          if (response.code === 0) {
            this.classList = response.data || [];
            
            // 如果班级列表不为空且当前没有选中任何班级，自动选择第一个班级
            if (this.classList.length > 0) {
              const firstClassId = this.classList[0].id;
              
              // 确保所有班级选择器都有默认值
              if (!this.selectedClass) {
                this.selectedClass = firstClassId;
              }
              if (!this.parentCommentClass) {
                this.parentCommentClass = firstClassId;
              }
              if (!this.studentIndicatorClass) {
                this.studentIndicatorClass = firstClassId;
              }
            }
          } else {
            this.classList = [];
            console.error('获取班级数据失败:', response.msg);
          }
          return response; // 返回响应数据
        })
        .catch((err) => {
          console.error('获取班级数据失败:', err);
          this.classList = [];
          return Promise.reject(err); // 抛出错误以便外部可以捕获
        });
    },
    
    // 处理统一日期变更
    handleUnifiedDateChange(date) {
      this.selectedDate = date;
      // 日期变更时重新加载所有数据
      this.initCharts();
    },
    
    // 已替换为统一日期处理，此方法保留以备后用
    handleDateChange(date) {
      this.handleUnifiedDateChange(date);
    },
    
    // 处理班级筛选变化
    handleClassChange(classId) {
      this.selectedClass = classId;
      // 直接调用initCharts初始化图表，避免递归调用handleSectionChange
      this.$nextTick(() => {
        this.initCharts();
      });
    },
    
    // 日期已统一，此方法保留但使用统一日期
    handleParentCommentDateChange(date) {
      this.handleUnifiedDateChange(date);
    },
    
    // 处理家长说班级筛选变化
    handleParentCommentClassChange(classId) {
      this.parentCommentClass = classId;
      this.$nextTick(() => {
        // 根据日期和班级筛选家长留言数据 - 确保选择班级后内容会切换
        this.loadParentCommentsData();
      });
    },
    
    // 加载家长留言数据
    loadParentCommentsData() {
      // 构建请求参数，使用统一的日期选择器值
      const params = {
        date: this.formatDate(this.selectedDate),
        sectionId: this.activeSectionId,
        classId: this.parentCommentClass
      };
      
      // 调用API获取家长留言数据
      this.$fetch(api.getParentComments, params)
        .then((response) => {
          console.log('API响应完整数据:', response);
          if (response.code === 0) {
            // 处理返回的家长留言数据并更新studentsData
            // 确保获取的是response.data中的实际数据数组
            const actualData = response.data || [];
            console.log('准备处理的数据:', actualData);
            this.processParentCommentsData(actualData);
            
            // 强制刷新computed属性
            this.$forceUpdate();
          } else {
            console.error('获取家长留言数据失败:', response.msg);
            // 显示空数据
            this.processParentCommentsData([]);
          }
        })
        .catch((err) => {
          console.error('获取家长留言数据失败:', err);
        });
    },
    
    // 处理家长留言数据
    processParentCommentsData(data) {
      // 根据实际API返回的数据结构进行处理
      // API返回格式: [{id, student_name, content, create_time}]
      console.log('原始API数据:', data);
      
      // 创建一个新的parentCommentsData数组来存储实际的家长留言数据
      const newParentCommentsData = [];
      
      if (data && Array.isArray(data)) {
        // 直接将API返回的数据转换为前端需要的格式
        data.forEach(item => {
          newParentCommentsData.push({
            id: item.id,
            name: item.student_name,
            className: item.className || '', // 从API获取或默认为空
            parentComments: [
              {
                time: this.formatTimestamp(item.create_time),
                content: item.content || "暂无留言"
              }
            ]
          });
        });
      }
      
      // 替换整个parentCommentsData数组
      this.parentCommentsData = newParentCommentsData;
      console.log('处理后的parentCommentsData:', this.parentCommentsData);
    },
    
    // 格式化时间戳为日期时间字符串
    formatTimestamp(timestamp) {
      if (!timestamp) return '';
      const d = new Date(timestamp * 1000); // 假设是秒级时间戳
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      const hours = String(d.getHours()).padStart(2, '0');
      const minutes = String(d.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    
    // 格式化日期为YYYY-MM-DD格式
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      // 使用传统方式补零，避免padStart兼容性问题
      const month = (d.getMonth() + 1) < 10 ? '0' + (d.getMonth() + 1) : (d.getMonth() + 1);
      const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
      return `${year}-${month}-${day}`;
    },
    
    // 日期已统一，此方法保留但使用统一日期
    handleStudentIndicatorDateChange(date) {
      this.handleUnifiedDateChange(date);
    },
    
    // 处理幼儿个体动态班级筛选变化
    handleStudentIndicatorClassChange(classId) {
      this.studentIndicatorClass = classId;
      this.$nextTick(() => {
        this.initStudentIndicators();
      });
    },

    // 处理年段切换
    handleSectionChange(tab) {
      // 确保activeSectionId被正确更新，如果有tab参数才使用tab.name
      if (tab) {
        this.activeSectionId = tab.name;
      }
      
      // 先销毁当前的图表实例，避免内存泄漏
      if (this.teacherReportChart) {
        this.teacherReportChart.dispose();
        this.teacherReportChart = null;
      }
      if (this.parentInteractionChart) {
        this.parentInteractionChart.dispose();
        this.parentInteractionChart = null;
      }
      if (this.feedbackTypeChart) {
        this.feedbackTypeChart.dispose();
        this.feedbackTypeChart = null;
      }
      
      this.$nextTick(() => {
        // 加载对应年段的班级列表
        this.loadClassList().then(() => {
          // 确保在年段切换时，如果有班级，自动选择第一个班级
          if (this.classList.length > 0) {
            // 自动选择当前年段的第一个班级
            const firstClassId = this.classList[0].id;
            
            // 设置所有模块的班级选择器为第一个班级
            this.parentCommentClass = firstClassId;
            this.studentIndicatorClass = firstClassId;
            this.selectedClass = firstClassId;
          }
          
          // 班级数据加载完成后，等待DOM完全更新再初始化图表
          this.$nextTick(() => {
            this.initCharts();
            
            // 强制图表重新计算大小
            this.$nextTick(() => {
              this.resizeCharts();
            });
          });
        });
      });
    },

    // 初始化所有图表
    initCharts() {
      // 加载教师填报统计数据
      this.loadTeacherReportData();
      
      // 加载家长互动统计数据
      this.loadParentInteractionData();
      
      // 注意：全段指标动态数据由SectionIndicatorsTable组件内部自动加载
      // 不再需要手动调用loadSectionIndicators()
      
      // 加载幼儿个体动态数据
      this.loadStudentIndicatorsData();
      
      // 加载家长说数据 - 确保页面初始化时就加载家长留言
      this.loadParentCommentsData();
      
      // 初始化反馈类型图表（不使用模拟数据）
      this.initFeedbackTypeChart();
    },
    
    // 调整所有图表大小 - 使用统一的处理函数
    resizeCharts() {
      this.handleChartResize();
    },
    
    // 加载教师填报统计数据
    loadTeacherReportData() {
      const params = {
        date: this.formatDate(this.selectedDate),
        sectionId: this.activeSectionId
        // 移除classId参数，显示整个年段的教师填报统计数据
      };
      
      this.$fetch(api.getTeacherReportData, params)
        .then((response) => {
          console.log(response, '教师填报统计数据');
          if (response.code === 0 && response.data && response.data.chart_data) {
            // 从新格式中提取chart_data数组
            this.initTeacherReportChart(response.data.chart_data);
          } else if (response.code === 0 && response.data) {
            // 兼容旧格式
            this.initTeacherReportChart(response.data);
          } else {
            // 使用模拟数据作为备份
            this.initTeacherReportChart();
          }
        })
        .catch((err) => {
          console.error('获取教师填报统计数据失败:', err);
          // 使用模拟数据作为备份
          this.initTeacherReportChart();
        });
    },
    
    // 加载家长互动统计数据
    loadParentInteractionData() {
      const params = {
        date: this.formatDate(this.selectedDate),
        sectionId: this.activeSectionId
        // 移除classId参数，显示整个年段的家长互动统计数据
      };
      
      this.$fetch(api.getParentInteractionData, params)
        .then((response) => {
          console.log(response, '家长互动统计数据');
          if (response.code === 0 && response.data) {
            this.initParentInteractionChart(response.data);
          } else {
            // 使用模拟数据作为备份
            this.initParentInteractionChart();
          }
        })
        .catch((err) => {
          console.error('获取家长互动统计数据失败:', err);
          // 使用模拟数据作为备份
          this.initParentInteractionChart();
        });
    },
    
    // 加载幼儿个体动态数据
    loadStudentIndicatorsData() {
      const params = {
        date: this.formatDate(this.selectedDate), // 使用统一的日期选择器值
        sectionId: this.activeSectionId,
        classId: this.studentIndicatorClass
      };
      
      this.$fetch(api.getStudentIndicatorsData, params)
        .then((response) => {
          console.log(response, '幼儿个体动态数据');
          if (response.code === 0 && response.data) {
            this.studentIndicatorsData = response.data;
          } else {
            this.studentIndicatorsData = [];
          }
          this.initStudentIndicators();
        })
        .catch((err) => {
          console.error('获取幼儿个体动态数据失败:', err);
          this.studentIndicatorsData = [];
          this.initStudentIndicators();
        });
    },

    // 初始化教师填报统计柱状图
    initTeacherReportChart(reportData = null) {
      // 只使用传入的数据，不使用模拟数据
      const data = reportData || [];
      
      // 使用Vue的$nextTick确保DOM已更新
      this.$nextTick(() => {
          // 使用ref直接获取DOM元素，更可靠
          let chartDom = this.$refs.teacherReportChart;
          
          // 增强的DOM元素检查
          if (!chartDom) {
            console.error('教师填报统计图表容器未找到');
            return;
          }
          
          // 处理ref可能返回数组的情况（因为在v-for中）
          if (Array.isArray(chartDom)) {
            // 找到当前激活选项卡对应的图表容器
            // 由于ref在v-for中是按顺序生成的，我们需要找到正确的索引
            const activeIndex = this.sectionList.findIndex(
              section => section.id.toString() === this.activeSectionId
            );
            if (activeIndex === -1) {
              console.error('未找到当前激活的年段索引');
              return;
            }
            chartDom = chartDom[activeIndex];
            if (!chartDom) {
              console.error('当前激活年段的教师填报统计图表容器未找到');
              return;
            }
          }
          
          // 处理ref可能返回组件实例而不是DOM元素的情况
          if (chartDom.$el) {
            chartDom = chartDom.$el;
          }
          
          // 确保是有效的DOM元素
          if (!(chartDom instanceof HTMLElement)) {
            console.error('教师填报统计图表容器不是有效的DOM元素', chartDom);
            return;
          }
        
        // 检查元素是否可见
        if (chartDom.offsetParent === null) {
          console.error('教师填报统计图表容器不可见');
          return;
        }
        
        // 检查元素宽高
        let rect;
        try {
          rect = chartDom.getBoundingClientRect();
          if (rect.width <= 0 || rect.height <= 0) {
            console.error('教师填报统计图表容器宽高为0，无法初始化', rect);
            return;
          }
        } catch (e) {
          console.error('获取教师填报统计图表容器尺寸失败:', e);
          return;
        }
        
        // 确保元素有正确的样式
        if (chartDom.style.width === '0px' || chartDom.style.height === '0px') {
          console.error('教师填报统计图表容器样式宽高为0');
          return;
        }
        
        // 销毁旧图表实例
        if (this.teacherReportChart) {
          try {
            this.teacherReportChart.dispose();
          } catch (e) {
            console.error('销毁教师填报统计图表实例失败:', e);
          }
          this.teacherReportChart = null;
        }
        
        // 初始化新图表实例
        try {
          this.teacherReportChart = echarts.init(chartDom);
          
          // 监听窗口大小变化
          window.addEventListener('resize', this.handleChartResize);
          
          // 设置图表选项
          const option = {
            tooltip: {
              trigger: "axis",
              axisPointer: {
                type: "shadow",
              },
              formatter: function (params) {
                let result = params[0].name + "<br/>";
                let requiredValue = 0;
                let completedValue = 0;
                params.forEach((param) => {
                  if (param.seriesName === "已填报") {
                    completedValue = param.value;
                  } else if (param.seriesName === "未填报") {
                    // 未填报是自动计算的，不需要从参数中获取
                  }
                  result +=
                    param.marker + param.seriesName + ": " + param.value + "<br/>";
                });
                requiredValue = completedValue + (params[1] ? params[1].value : 0);
                const completionRate = (
                  (completedValue / requiredValue) *
                  100
                ).toFixed(1);
                result += "应填报: " + requiredValue + "<br/>";
                result += "完成率: " + completionRate + "%";
                return result;
              },
            },
            legend: {
              data: ["已填报", "未填报"],
            },
            grid: {
              left: "3%",
              right: "4%",
              bottom: "3%",
              containLabel: true,
            },
            xAxis: {
              type: "category",
              data: data.map((item) => item.name),
              axisLabel: {
                interval: 0,
                rotate: 30,
              },
            },
            yAxis: {
              type: "value",
            },
            series: [
              {
                name: "已填报",
                type: "bar",
                stack: "total",
                emphasis: {
                  focus: "series",
                },
                data: data.map((item) => item.completed),
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: "#83bff6" },
                    { offset: 0.5, color: "#188df0" },
                    { offset: 1, color: "#188df0" },
                  ]),
                },
                barWidth: "40%", // 改细一点
                label: {
                  show: true,
                  position: "inside",
                  formatter: "{c}人",
                  color: "#fff",
                  fontSize: 12,
                },
              },
              {
                name: "未填报",
                type: "bar",
                stack: "total",
                emphasis: {
                  focus: "series",
                },
                data: data.map((item) => item.required - item.completed),
                itemStyle: {
                  color: "#FF6E76",
                },
                barWidth: "40%",
                label: {
                  show: true,
                  position: "inside",
                  formatter: "{c}人",
                  color: "#fff",
                  fontSize: 12,
                },
              },
            ],
          };
          
          this.teacherReportChart.setOption(option, true);
          console.log('教师填报统计图表初始化成功');
        } catch (e) {
          console.error('初始化教师填报统计图表失败:', e);
        }
      });
    },

    // 初始化家长互动统计柱状图
    initParentInteractionChart(interactionData = null) {
      // 只使用传入的数据，不使用模拟数据
      const data = interactionData || [];
      
      // 使用Vue的$nextTick确保DOM已更新
      this.$nextTick(() => {
          // 使用ref直接获取DOM元素
          let chartDom = this.$refs.parentInteractionChart;
          
          // 增强的DOM元素检查
          if (!chartDom) {
            console.error('家长互动统计图表容器未找到');
            return;
          }
          
          // 处理ref可能返回数组的情况（因为在v-for中）
          if (Array.isArray(chartDom)) {
            // 找到当前激活选项卡对应的图表容器
            // 由于ref在v-for中是按顺序生成的，我们需要找到正确的索引
            const activeIndex = this.sectionList.findIndex(
              section => section.id.toString() === this.activeSectionId
            );
            if (activeIndex === -1) {
              console.error('未找到当前激活的年段索引');
              return;
            }
            chartDom = chartDom[activeIndex];
            if (!chartDom) {
              console.error('当前激活年段的家长互动统计图表容器未找到');
              return;
            }
          }
          
          // 处理ref可能返回组件实例而不是DOM元素的情况
          if (chartDom.$el) {
            chartDom = chartDom.$el;
          }
          
          // 确保是有效的DOM元素
          if (!(chartDom instanceof HTMLElement)) {
            console.error('家长互动统计图表容器不是有效的DOM元素', chartDom);
            return;
          }
        
        // 检查元素是否可见
        if (chartDom.offsetParent === null) {
          console.error('家长互动统计图表容器不可见');
          return;
        }
        
        // 检查元素宽高
        let rect;
        try {
          rect = chartDom.getBoundingClientRect();
          if (rect.width <= 0 || rect.height <= 0) {
            console.error('家长互动统计图表容器宽高为0，无法初始化', rect);
            return;
          }
        } catch (e) {
          console.error('获取家长互动统计图表容器尺寸失败:', e);
          return;
        }
        
        // 确保元素有正确的样式
        if (chartDom.style.width === '0px' || chartDom.style.height === '0px') {
          console.error('家长互动统计图表容器样式宽高为0');
          return;
        }
        
        // 销毁旧图表实例
        if (this.parentInteractionChart) {
          try {
            this.parentInteractionChart.dispose();
          } catch (e) {
            console.error('销毁家长互动统计图表实例失败:', e);
          }
          this.parentInteractionChart = null;
        }
        
        // 初始化新图表实例
        try {
          this.parentInteractionChart = echarts.init(chartDom);
          
          // 监听窗口大小变化
          window.addEventListener('resize', this.handleChartResize);
          
          // 提取班级名称作为x轴数据
          const classNames = data.map((item) => item.name);

          // 准备柱状图数据
          const readData = data.map((item) => item.read);
          const unreadData = data.map((item) => item.unread);
          const reportedData = data.map((item) => item.reported);
          const unreportedData = data.map((item) => item.total - item.reported);

          // 计算百分比数据用于标签显示
          const readRates = data.map((item) =>
            Math.round((item.read / item.total) * 100)
          );
          const reportedRates = data.map((item) =>
            Math.round((item.reported / item.total) * 100)
          );
          const unreportedRates = data.map((item) =>
            Math.round(((item.total - item.reported) / item.total) * 100)
          );

          // 设置图表选项
          const option = {
            tooltip: {
              trigger: "axis",
              axisPointer: {
                type: "shadow",
              },
              formatter: function (params) {
                const classIndex = params[0].dataIndex;
                const classItem = data[classIndex];
                const readRate = readRates[classIndex];
                const reportedRate = reportedRates[classIndex];

                return `
                  <div style="padding: 8px;">
                    <div><strong>${classItem.name}</strong></div>
                    <div>总人数: ${classItem.total}</div>
                    <div>已读: ${classItem.read} (${readRate}%)</div>
                    <div>已填报: ${classItem.reported} (${reportedRate}%)</div>
                    <div>未读: ${classItem.unread}</div>
                  </div>
                `;
              },
            },
            legend: {
              data: ["已读家长", "未读家长", "已填报家长", "未填报家长"],
              top: 0,
            },
            grid: {
              left: "3%",
              right: "4%",
              bottom: "3%",
              containLabel: true,
            },
            xAxis: {
              type: "category",
              data: classNames,
              axisLabel: {
                interval: 0,
                rotate: 0,
              },
            },
            yAxis: {
              type: "value",
              name: "人数",
            },
            series: [
              {
                name: "已读家长",
                type: "bar",
                stack: "家长状态",
                data: readData,
                itemStyle: {
                  color: "#5470c6",
                },
                label: {
                  show: true,
                  position: "inside",
                  formatter: function (params) {
                    return params.value + "人";
                  },
                  fontSize: 10,
                  color: "#fff",
                },
              },
              {
                name: "未读家长",
                type: "bar",
                stack: "家长状态",
                data: unreadData,
                itemStyle: { color: "#89a6e6" }, // 已读家长颜色#5470c6的浅色系
                label: {
                  show: true,
                  position: "inside",
                  formatter: function (params) {
                    return params.value + "人";
                  },
                  fontSize: 10,
                  color: "#fff",
                },
              },
              {
                name: "已填报家长",
                type: "bar",
                stack: "填报状态",
                data: reportedData,
                itemStyle: {
                  color: "#fac858",
                },
                label: {
                  show: true,
                  position: "inside",
                  formatter: function (params) {
                    return params.value + "人";
                  },
                  fontSize: 10,
                  color: "#fff",
                },
              },
              {
                name: "未填报家长",
                type: "bar",
                stack: "填报状态",
                data: unreportedData,
                itemStyle: {
                  color: "#fbe2a8", // 已填报家长颜色#fac858的浅色系
                },
                label: {
                  show: true,
                  position: "inside",
                  formatter: function (params) {
                    return params.value + "人";
                  },
                  fontSize: 10,
                  color: "#fff",
                },
              },
            ],
          };
          
          this.parentInteractionChart.setOption(option, true);
          console.log('家长互动统计图表初始化成功');
        } catch (e) {
          console.error('初始化家长互动统计图表失败:', e);
        }
      });
    },

    // 初始化完成率柱状图
    initCompletionRateChart() {
      console.log(this.selectedDate, '完成了柱状图');
      // 注意：年段事项配置由SectionIndicatorsTable组件内部自动加载
      // 不再需要手动调用loadSectionIndicators()
    },

    // 加载年段指标配置 - 现在由SectionIndicatorsTable组件管理
    // loadSectionIndicators() { ... },
    
    // 解析年段指标数据，适配层级化数据结构（支持一级选项和二级子选项）
    parseSectionIndicators(data) {
      console.log('原始指标数据:', data);
      const result = [];
      
      try {
        // 检查数据是否为数组格式
        if (Array.isArray(data) && data.length > 0) {
          // 遍历每个指标
          data.forEach(indicatorItem => {
            // 检查必要字段是否存在
            if (indicatorItem.id && indicatorItem.name && Array.isArray(indicatorItem.optionSelections)) {
              // 创建指标对象
              const indicator = {
                id: indicatorItem.id,
                name: indicatorItem.name,
                optionSelections: [],
                avgValue: indicatorItem.avgValue || 0
              };
              
              // 检查是否有选项数据
              if (indicatorItem.optionSelections && indicatorItem.optionSelections.length > 0) {
                // 按主选项分组，确保数据结构一致性
                const optionGroups = {};
                
                // 处理层级化选项结构
                indicatorItem.optionSelections.forEach(selection => {
                  if (selection.option) {
                    // 获取主选项名称作为子项目名称
                    const subProjectName = selection.option;
                    
                    if (!optionGroups[subProjectName]) {
                      optionGroups[subProjectName] = {
                        name: subProjectName, // 使用一级选项作为子项目名称
                        options: [] // 初始化空选项数组，将使用subOptions填充
                      };
                    }
                    
                    // 优先处理subOptions数据作为选项数组
                    if (selection.subOptions && Array.isArray(selection.subOptions) && selection.subOptions.length > 0) {
                      console.log('处理subOptions数据:', selection.subOptions);
                      selection.subOptions.forEach(subOption => {
                        // 确保子选项数据有效性
                        if (subOption && (subOption.option || subOption.name)) {
                          const optionName = subOption.option || subOption.name;
                          optionGroups[subProjectName].options.push({
                            name: optionName,
                            count: subOption.count || 0,
                            percentage: subOption.percentage || 0,
                            unit: ''
                          });
                          console.log(`添加子选项: ${optionName}, 计数: ${subOption.count}, 百分比: ${subOption.percentage}`);
                        }
                      });
                    } else {
                      // 如果没有subOptions，则使用当前选项作为选项数据
                      optionGroups[subProjectName].options.push({
                        name: selection.option,
                        count: selection.count || 0,
                        percentage: selection.percentage || 0,
                        unit: ''
                      });
                    }
                  }
                });
                
                // 将分组后的子项目添加到indicator中
                for (const key in optionGroups) {
                  if (optionGroups.hasOwnProperty(key)) {
                    indicator.optionSelections.push(optionGroups[key]);
                  }
                }
              }
              
              // 确保即使没有子项目，也添加一个默认的子项目结构
              if (indicator.optionSelections.length === 0) {
                indicator.optionSelections.push({
                  name: '暂无数据',
                  options: []
                });
              }
              
              // 添加到结果集
              result.push(indicator);
            }
          });
        }
        
        console.log('解析后的指标数据:', result);
        
        return result;
      } catch (error) {
        console.error('解析年段指标数据出错:', error);
        return [];
      }
    },
    
    // 解析选项统计数据 - 现在由SectionIndicatorsTable组件管理
    // parseOptionStatsData(data) { ... },

    // 生成模拟指标数据（两级结构）
    generateMockIndicators() {
      // 模拟事项配置数据 - 更符合Excel格式展示的模拟数据
      const mockIndicators = [
        {
          id: "1",
          name: "入园环节",
          options: ["适应情况", "情绪状态"],
          optionSelections: [
            {
              option: "适应情况",
              count: 35,
              level: 1,
              subOptions: [
                { name: "主动入园", count: 35, percentage: 35 },
                { name: "需牵手入园", count: 25, percentage: 25 },
                { name: "哭闹入园", count: 40, percentage: 40 }
              ]
            },
            {
              option: "情绪状态",
              count: 87,
              level: 2,
              subOptions: [
                { name: "非常好", count: 25, percentage: 15 },
                { name: "良好", count: 30, percentage: 35 },
                { name: "加油", count: 12, percentage: 10 },
                { name: "需安抚", count: 10, percentage: 9 }
              ]
            }
          ],
          avgValue: 1.5
        },
        {
          id: "2",
          name: "晨间活动",
          options: ["参与度", "互动情况"],
          optionSelections: [
            {
              option: "参与度",
              count: 30,
              level: 1,
              subOptions: [
                { name: "积极主动", count: 15, percentage: 50 },
                { name: "需引导参与", count: 10, percentage: 33 },
                { name: "观望犹豫", count: 5, percentage: 17 }
              ]
            },
            {
              option: "互动情况",
              count: 30,
              level: 2,
              subOptions: [
                { name: "主动分享玩具", count: 10, percentage: 33 },
                { name: "跟随同伴游戏", count: 15, percentage: 50 },
                { name: "独自玩耍", count: 5, percentage: 17 }
              ]
            }
          ],
          avgValue: 1.8
        },
        {
          id: "3",
          name: "盥洗晨点",
          options: ["早点", "盥洗完点"],
          optionSelections: [
            {
              option: "早点",
              count: 30,
              level: 1,
              subOptions: [
                { name: "全部吃完", count: 20, percentage: 67 },
                { name: "剩余少量", count: 8, percentage: 27 },
                { name: "未吃完", count: 2, percentage: 6 }
              ]
            },
            {
              option: "盥洗完点",
              count: 30,
              level: 2,
              subOptions: [
                { name: "独立完成", count: 15, percentage: 50 },
                { name: "需少量提醒", count: 12, percentage: 40 },
                { name: "需协助完成", count: 3, percentage: 10 }
              ]
            }
          ],
          avgValue: 1.2
        },
        {
          id: "4",
          name: "游戏活动",
          options: ["兴趣区域", "专注时长"],
          optionSelections: [
            {
              option: "兴趣区域",
              count: 30,
              level: 1,
              subOptions: [
                { name: "建构区", count: 12, percentage: 40 },
                { name: "涂鸦区", count: 8, percentage: 27 },
                { name: "阅读区", count: 6, percentage: 20 },
                { name: "操作区", count: 4, percentage: 13 }
              ]
            },
            {
              option: "专注时长",
              count: 30,
              level: 2,
              subOptions: [
                { name: "专注时长", count: 15, percentage: 50, unit: "分钟" },
                { name: "均值", count: 20, percentage: 67, unit: "分钟" }
              ]
            }
          ],
          avgValue: 1.5
        },
        {
          id: "5",
          name: "午餐环节",
          options: ["进餐状态", "自主能力"],
          optionSelections: [
            {
              option: "进餐状态",
              count: 30,
              level: 1,
              subOptions: [
                { name: "吃得好", count: 15, percentage: 50 },
                { name: "基本吃完", count: 10, percentage: 33 },
                { name: "胃口一般", count: 3, percentage: 10 },
                { name: "进食缓慢", count: 2, percentage: 7 }
              ]
            },
            {
              option: "自主能力",
              count: 30,
              level: 2,
              subOptions: [
                { name: "独立进食", count: 18, percentage: 60 },
                { name: "需少量喂饭", count: 10, percentage: 33 },
                { name: "依赖喂饭", count: 2, percentage: 7 }
              ]
            }
          ],
          avgValue: 1.6
        },
        {
          id: "6",
          name: "饮水情况",
          options: ["当日饮水量", "饮水主动性"],
          optionSelections: [
            {
              option: "当日饮水量",
              count: 30,
              level: 1,
              subOptions: [
                { name: "饮水量", count: 3, percentage: 10, unit: "杯" },
                { name: "均值", count: 200, percentage: 67, unit: "ml" }
              ]
            },
            {
              option: "饮水主动性",
              count: 30,
              level: 2,
              subOptions: [
                { name: "主动要求喝水", count: 15, percentage: 50 },
                { name: "需提醒喝水", count: 12, percentage: 40 },
                { name: "不爱喝水", count: 3, percentage: 10 }
              ]
            }
          ],
          avgValue: 1.4
        },
        {
          id: "7",
          name: "如厕环节",
          options: ["大小便", "排便时间", "自主如厕"],
          optionSelections: [
            {
              option: "大小便",
              count: 30,
              level: 1,
              subOptions: [
                { name: "正常", count: 25, percentage: 83 },
                { name: "尿频", count: 2, percentage: 7 },
                { name: "尿少", count: 2, percentage: 7 },
                { name: "无", count: 1, percentage: 3 }
              ]
            },
            {
              option: "排便时间",
              count: 30,
              level: 2,
              subOptions: [
                { name: "排便时间", count: 5, percentage: 17, unit: "分钟" },
                { name: "均值", count: 3, percentage: 10, unit: "分钟" }
              ]
            },
            {
              option: "自主如厕",
              count: 30,
              level: 3,
              subOptions: [
                { name: "独立完成", count: 20, percentage: 67 },
                { name: "需提醒", count: 8, percentage: 27 },
                { name: "需全程协助", count: 2, percentage: 6 }
              ]
            }
          ],
          avgValue: 1.8
        },
        {
          id: "8",
          name: "午睡情况",
          options: ["睡眠状态", "入睡时长", "睡眠表现"],
          optionSelections: [
            {
              option: "睡眠状态",
              count: 30,
              level: 1,
              subOptions: [
                { name: "良好", count: 20, percentage: 67 },
                { name: "待提高", count: 5, percentage: 17 },
                { name: "有进步", count: 4, percentage: 13 },
                { name: "入睡困难", count: 1, percentage: 3 }
              ]
            },
            {
              option: "入睡时长",
              count: 30,
              level: 2,
              subOptions: [
                { name: "入睡时长", count: 15, percentage: 50, unit: "分钟" },
                { name: "午睡总时长", count: 1.5, percentage: 50, unit: "小时" }
              ]
            },
            {
              option: "睡眠表现",
              count: 30,
              level: 3,
              subOptions: [
                { name: "安静入睡", count: 22, percentage: 73 },
                { name: "需安抚物", count: 5, percentage: 17 },
                { name: "中途觉醒", count: 2, percentage: 7 },
                { name: "打鼾", count: 1, percentage: 3 }
              ]
            }
          ],
          avgValue: 1.6
        }
      ];
      return mockIndicators;
    },

    // 计算百分比 - 支持两种调用方式：
    // 1. getPercentage(optionSelections数组, index) - 计算数组中特定索引项占总和的百分比
    // 2. getPercentage(value, total) - 计算某个值占总数的百分比
    getPercentage(value, total) {
      // 处理第一种情况：如果value是数组，则计算数组中total索引位置的元素占总和的百分比
      if (Array.isArray(value)) {
        if (!value || value.length === 0) return 0;
        const arrayTotal = value.reduce((sum, item) => sum + (item.count || 0), 0);
        if (arrayTotal === 0) return 0;
        return ((value[total]?.count || 0) / arrayTotal * 100).toFixed(1);
      }
      
      // 处理第二种情况：计算单个值占总数的百分比
      if (typeof value !== 'number' || typeof total !== 'number' || total === 0) return 0;
      return ((value / total) * 100).toFixed(1);
    },
    
    // 计算每个事项需要合并的总行数
    getTotalRowspan(indicator) {
      if (!indicator.optionSelections) return 1;
      
      let totalRows = 0;
      
      // 每个子项目占1行，如果有选项再额外占1行（所有选项在一行显示）
      indicator.optionSelections.forEach(subProject => {
        totalRows += 1; // 子项目行
        if (subProject.options && subProject.options.length > 0) {
          totalRows += 1; // 选项统计行（所有选项在一行）
        }
      });
      
      return totalRows;
    },
    
    // 导出Excel - 现在由SectionIndicatorsTable组件管理
    // exportExcel() { ... },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    // 渲染横向柱状图（备用，暂时不使用）
    renderHorizontalBarChart() {
      const chartDom = document.getElementById("completionRateChart");
      // 确保DOM元素存在
      if (!chartDom) {
        console.warn('完成率图表容器不存在');
        return;
      }
      if (this.completionRateChart) {
        this.completionRateChart.dispose();
      }
      this.completionRateChart = echarts.init(chartDom);

      // 准备图表数据
      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: function (params) {
            const indicator = this.indicatorsData.find(
              (item) => item.name === params[0].name
            );
            let result = params[0].name + "<br/>";
            result +=
              params[0].marker + "年段平均值: " + params[0].value + "%<br/>";
            if (indicator && indicator.options && indicator.optionValues) {
              result += "<br/>选项详情:<br/>";
              indicator.options.forEach((opt, index) => {
                result += opt + ": " + indicator.optionValues[index] + "%<br/>";
              });
            }
            return result;
          }.bind(this),
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          top: "10%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
          max: 100,
          axisLabel: {
            formatter: "{value}%",
          },
        },
        yAxis: {
          type: "category",
          data: this.indicatorsData.map((item) => item.name),
          axisLabel: {
            interval: 0,
          },
        },
        series: [
          {
            name: "年段平均值",
            type: "bar",
            data: this.indicatorsData.map((item) => ({
              value: item.avgValue,
              // 根据不同的完成率设置不同的颜色
              itemStyle: {
                color: function (params) {
                  if (params.value >= 90) return "#52c41a";
                  if (params.value >= 70) return "#1890ff";
                  return "#ff4d4f";
                },
              },
            })),
            barWidth: "60%",
            label: {
              show: true,
              position: "right",
              formatter: "{c}%",
              fontSize: 12,
            },
          },
        ],
      };

      this.completionRateChart.setOption(option);
    },

    // 初始化反馈事项分布饼图
    // 初始化反馈类型统计饼图
    initFeedbackTypeChart(feedbackTypeData = null) {
      // 只使用传入的数据，不使用模拟数据
      const data = feedbackTypeData || [];
      
      // 使用Vue的$nextTick确保DOM已更新
      this.$nextTick(() => {
          // 使用ref直接获取DOM元素
          let chartDom = this.$refs.feedbackTypeChart;
          
          // 增强的DOM元素检查
          if (!chartDom) {
            console.error('反馈类型统计图表容器未找到');
            return;
          }
          
          // 处理ref可能返回数组的情况（因为在v-for中）
          if (Array.isArray(chartDom)) {
            // 找到当前激活选项卡对应的图表容器
            // 由于ref在v-for中是按顺序生成的，我们需要找到正确的索引
            const activeIndex = this.sectionList.findIndex(
              section => section.id.toString() === this.activeSectionId
            );
            if (activeIndex === -1) {
              console.error('未找到当前激活的年段索引');
              return;
            }
            chartDom = chartDom[activeIndex];
            if (!chartDom) {
              console.error('当前激活年段的反馈类型统计图表容器未找到');
              return;
            }
          }
          
          // 处理ref可能返回组件实例而不是DOM元素的情况
          if (chartDom.$el) {
            chartDom = chartDom.$el;
          }
          
          // 确保是有效的DOM元素
          if (!(chartDom instanceof HTMLElement)) {
            console.error('反馈类型统计图表容器不是有效的DOM元素', chartDom);
            return;
          }
        
        // 检查元素是否可见
        if (chartDom.offsetParent === null) {
          console.error('反馈类型统计图表容器不可见');
          return;
        }
        
        // 检查元素宽高
        let rect;
        try {
          rect = chartDom.getBoundingClientRect();
          if (rect.width <= 0 || rect.height <= 0) {
            console.error('反馈类型统计图表容器宽高为0，无法初始化', rect);
            return;
          }
        } catch (e) {
          console.error('获取反馈类型统计图表容器尺寸失败:', e);
          return;
        }
        
        // 确保元素有正确的样式
        if (chartDom.style.width === '0px' || chartDom.style.height === '0px') {
          console.error('反馈类型统计图表容器样式宽高为0');
          return;
        }
        
        // 销毁旧图表实例
        if (this.feedbackTypeChart) {
          try {
            this.feedbackTypeChart.dispose();
          } catch (e) {
            console.error('销毁反馈类型统计图表实例失败:', e);
          }
          this.feedbackTypeChart = null;
        }
        
        // 初始化新图表实例
        try {
          this.feedbackTypeChart = echarts.init(chartDom);
          
          // 监听窗口大小变化
          window.addEventListener('resize', this.handleChartResize);
          
          // 设置图表选项
          const option = {
            tooltip: {
              trigger: "item",
              formatter: "{a} <br/>{b}: {c} ({d}%)",
            },
            legend: {
              orient: "vertical",
              left: "left",
            },
            series: [
              {
                name: "反馈类型",
                type: "pie",
                radius: "60%",
                center: ["50%", "50%"],
                data: data,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: "rgba(0, 0, 0, 0.5)",
                  },
                },
              },
            ],
          };
          
          this.feedbackTypeChart.setOption(option, true);
          console.log('反馈类型统计图表初始化成功');
        } catch (e) {
          console.error('初始化反馈类型统计图表失败:', e);
        }
      });
    },
    
    // 统一处理图表大小调整
    handleChartResize() {
      try {
        if (this.teacherReportChart) {
          this.teacherReportChart.resize();
        }
        if (this.parentInteractionChart) {
          this.parentInteractionChart.resize();
        }
        if (this.feedbackTypeChart) {
          this.feedbackTypeChart.resize();
        }
        // 调整幼儿个体动态图表大小
        Object.values(this.studentCharts).forEach((chart) => {
          if (chart) {
            chart.resize();
          }
        });
      } catch (e) {
        console.error('调整图表大小失败:', e);
      }
    },

    // 初始化学生指标展示
    initStudentIndicators() {
      // 销毁现有图表
      Object.values(this.studentCharts).forEach((chart) => {
        if (chart) {
          chart.dispose();
        }
      });
      this.studentCharts = {};

      // 直接使用从API获取的学生指标数据
      let filteredData = [...this.studentIndicatorsData];
      
      // 根据筛选条件过滤数据
      if (this.studentIndicatorClass) {
        // 找到对应的班级名称
        const selectedClassName = this.classList.find(cls => cls.id === this.studentIndicatorClass)?.className || '';
        // 直接使用班级名称进行过滤，确保班级直接用选中的班级名称
        filteredData = filteredData.filter(student => student.className === selectedClassName);
      }

      // 为每个学生创建图表
      setTimeout(() => {
        filteredData.forEach((student) => {
          this.renderStudentChart(student);
        });
      }, 100);
    },

    // 生成模拟学生数据
    generateMockStudentsData() {
      const students = [
        { id: "101", name: "张三", className: "小班1班" },
        { id: "102", name: "李四", className: "小班1班" },
        { id: "103", name: "王五", className: "小班1班" },
        { id: "104", name: "赵六", className: "小班1班" },
        { id: "105", name: "钱七", className: "小班1班" },
        { id: "106", name: "孙八", className: "小班1班" },
        { id: "107", name: "周九", className: "小班1班" },
        { id: "108", name: "吴十", className: "小班1班" },
      ];

      const colors = [
        "#1890ff",
        "#52c41a",
        "#faad14",
        "#f5222d",
        "#722ed1",
        "#fa8c16",
        "#13c2c2",
        "#eb2f96",
      ];

      // 获取指标配置
      const indicatorConfigs = [
        {
          name: "生活习惯",
          options: ["饮食情况", "睡眠质量", "如厕情况", "个人卫生"],
        },
        {
          name: "学习能力",
          options: ["注意力集中", "动手操作", "语言表达", "认知理解"],
        },
        {
          name: "社交互动",
          options: ["同伴交往", "合作分享", "情绪管理", "规则意识"],
        },
        {
          name: "健康状况",
          options: ["身体发育", "体能测试", "视力情况", "心理健康"],
        },
      ];

      return students.map((student, index) => {
        // 为每个学生生成指标数据
        const indicators = indicatorConfigs.map((indicator) => {
          // 为每个指标选项生成随机值
          const optionValues = indicator.options.map(
            () => Math.floor(Math.random() * 40) + 60
          );

          // 计算指标平均值
          const avgValue =
            optionValues.reduce((sum, val) => sum + val, 0) /
            optionValues.length;

          return {
            name: indicator.name,
            options: indicator.options,
            optionValues: optionValues,
            avgValue: Number(avgValue.toFixed(1)),
          };
        });

        return {
          ...student,
          avatarColor: colors[index % colors.length],
          indicators: indicators,
        };
      });
    },

    // 渲染学生个人指标图表 - 旭日图展示
    renderStudentChart(student) {
      const chartDom = document.getElementById(`studentChart_${student.id}`);
      // 确保DOM元素存在
      if (!chartDom) {
        console.warn(`学生${student.name}的图表容器不存在`);
        return;
      }

      // 销毁现有图表
      if (this.studentCharts[student.id]) {
        this.studentCharts[student.id].dispose();
      }

      // 创建新图表
      this.studentCharts[student.id] = echarts.init(chartDom);

      // 创建符合旭日图要求的标准数据结构
      // 使用嵌套对象而不是字符串或数组的混合结构
      const sunburstData = {
        name: student.name + '的发展指标',
        value: 100, // 根节点必须有value
        children: [] // 初始化空数组，然后填充有效的子项
      };

      // 安全地处理学生指标数据，确保每个节点都符合标准格式
      if (student.indicators && Array.isArray(student.indicators)) {
        student.indicators.forEach(indicator => {
          // 只处理有效指标对象
          if (indicator && indicator.name && Array.isArray(indicator.options)) {
            const validIndicator = {
              name: String(indicator.name),
              value: Number(indicator.avgValue || 0),
              children: []
            };

            // 处理二级选项，确保每个选项都有name和value
            indicator.options.forEach((option, index) => {
              if (option && typeof option === 'string') {
                validIndicator.children.push({
                name: String(option),
                value: Number(indicator.optionValues && indicator.optionValues[index] !== undefined ? indicator.optionValues[index] : 0)
              });
              }
            });

            // 只有当指标有子项时才添加到数据中
            if (validIndicator.children.length > 0) {
              sunburstData.children.push(validIndicator);
            }
          }
        });
      }

      // 准备图表数据 - 旭日图配置
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: function (info) {
            // 格式化提示信息
            let formatter = '';
            if (info.name) {
              formatter += info.name + '<br/>';
            }
            if (info.value !== undefined) {
              formatter += '数值: ' + info.value + '%<br/>';
            }
            if (info.data && info.data.children && info.data.children.length) {
              // 一级指标显示其包含的二级事项数量
              formatter += '包含事项: ' + info.data.children.length + '项';
            }
            return formatter;
          }
        },
        series: [
          {
            name: '幼儿个体动态',
            type: 'sunburst',
            radius: ['10%', '90%'], // 内圆和外圆半径范围
            center: ['50%', '50%'],
            data: [sunburstData], // 重要：将数据包装在数组中
            sort: null,
            emphasis: {
              focus: 'ancestor',
              label: {
                show: true,
                fontSize: '14'
              }
            },
            levels: [
              {
                // 根节点样式
                r0: '10%',
                r: '20%',
                label: {
                  fontSize: 14,
                  rotate: 0
                },
                itemStyle: {
                  borderWidth: 2
                }
              },
              {
                // 一级指标样式
                r0: '20%',
                r: '40%',
                label: {
                  fontSize: 12,
                  rotate: 'tangential'
                },
                itemStyle: {
                  borderWidth: 2
                }
              },
              {
                // 二级选项样式
                r0: '40%',
                r: '90%',
                label: {
                  fontSize: 10,
                  align: 'right',
                  padding: 3
                },
                itemStyle: {
                  borderWidth: 1
                }
              }
            ]
          }
        ]
      };

      // 应用配置
      this.studentCharts[student.id].setOption(option);
    }
  }
};
</script>

<style scoped>
/* 确保body和app-container有适当的样式 */
/deep/ .app-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/deep/ .box-card {
  flex: 1;
  display: flex;
}

/* 筛选器样式 */
.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  display: flex;
  gap: 10px;
}

.filter-container .el-date-editor {
  width: 240px;
}

.filter-container .el-select {
  width: 120px;
}

.tab-container {
  padding: 20px 0;
}

/* 图表容器 */
.chart-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 200px);
  min-height: 900px; /* 增加最小高度，确保有足够空间显示两行 */
  padding: 20px 0;
}

/* 主布局：两列 */
.main-layout {
  display: flex;
  gap: 20px;
  height: 100%;
}

/* 主布局容器 */
.main-layout {
  display: flex;
  height: 100%;
  gap: 20px;
  flex-wrap: nowrap;
}

/* 左侧列 */
.left-column {
  flex: 2;
  display: flex;
  flex-direction: column;
  gap: 20px;
  height: 100%;
}

/* 右侧列 - 强制占两行高度 */
.right-column {
  flex: 1;
  height: 100%; /* 强制占满整个容器高度，实现两行效果 */
  display: flex;
  flex-direction: column;
  position: relative;
}

/* 上方两个图表 */
.top-charts {
  display: flex;
  gap: 20px;
  height: 40%; /* 保持高度比例 */
}

/* 下方两栏布局 */
.bottom-sections {
  display: flex;
  gap: 20px;
  height: calc(60% - 20px); /* 调整高度，留出间隙 */
  min-height: 450px; /* 设置最小高度，确保有足够空间 */
}

/* 家长说区域 */
.parent-comments-section {
  flex: 1;
  height: 100%;
}

/* 幼儿个体动态区域 */
.student-indicators-section {
  flex: 1;
  height: 100%;
}

/* 家长说容器 */
.parent-comments-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  min-height: 0; /* 确保flex子元素可以正确收缩 */
}

/* 家长说滚动容器 */
.parent-comments-scroll-container {
  flex: 1;
  overflow-y: auto;
  padding-right: 10px;
  min-height: 0;
  max-height: 400px; /* 设置最大高度，确保可以滚动 */
  position: relative;
}

/* 留言内容单元格样式 */
.comment-content-cell {
  word-break: break-word;
  white-space: normal;
  line-height: 1.4;
}

/* 表格样式调整 */
/deep/ .el-table {
  font-size: 13px;
}

/deep/ .el-table__body {
  font-size: 12px;
}

/deep/ .el-table th {
  padding: 8px 0;
}

/deep/ .el-table td {
  padding: 10px 0;
}

/* 家长说卡片 */
.parent-comments-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 留言列表 */
.comments-list {
  margin-top: 15px;
}

/* 留言项 */
.comment-item {
  margin-bottom: 15px;
  padding: 12px;
  background: #f9f9f9;
  border-radius: 6px;
  border-left: 3px solid #409eff;
}

/* 留言时间 */
.comment-time {
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
}

/* 留言内容 */
.comment-content {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
  word-break: break-word;
}

/* 暂无留言提示 */
.no-comments {
  text-align: center;
  color: #999;
  padding: 20px;
  font-size: 14px;
}

/* 图表卡片通用样式 */
.chart-card {
  flex: 1;
  min-width: 300px;
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
}

/* 右侧图表样式 - 确保占满整个右侧列 */
.right-chart {
  height: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  height: 40px;
}

.chart {
  width: 100%;
  height: calc(100% - 40px);
  min-height: 200px; /* 设置最小高度 */
  flex: 1;
}

/* 学生指标展示样式 */
.student-indicators-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.students-scroll-container {
  flex: 1;
  overflow-y: auto;
  padding-right: 10px;
  min-height: 0;
  max-height: 400px; /* 设置最大高度以确保可以滚动 */
  position: relative;
}

.student-indicator-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.student-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.student-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
  font-weight: bold;
  margin-right: 15px;
}

.student-info {
  flex: 1;
}

.student-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.student-class {
  font-size: 14px;
  color: #666;
}

.student-chart {
  width: 100%;
  height: 250px; /* 适中的高度 */
}

/* 全屏按钮和全屏状态样式 */
.main-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

/* 全屏状态下的样式调整 */
:fullscreen .app-container,
:-webkit-full-screen .app-container,
:-moz-full-screen .app-container,
:-ms-fullscreen .app-container {
  padding: 30px;
  height: 100%;
  overflow: auto;
  background-color: #f0f2f5;
}

:fullscreen .chart,
:-webkit-full-screen .chart,
:-moz-full-screen .chart,
:-ms-fullscreen .chart {
  min-height: 300px;
}

:fullscreen .student-chart,
:-webkit-full-screen .student-chart,
:-moz-full-screen .student-chart,
:-ms-fullscreen .student-chart {
  min-height: 300px;
  height: auto;
}

:fullscreen .students-scroll-container,
:-webkit-full-screen .students-scroll-container,
:-moz-full-screen .students-scroll-container,
:-ms-fullscreen .students-scroll-container {
  max-height: 600px;
}

/* Excel样式表格样式 */
.excel-table-container {
  max-height: 800px;
  overflow-y: auto;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

.excel-style-table {
  width: 100%;
  border-collapse: collapse;
  background-color: #ffffff;
  font-size: 14px;
}

.excel-style-table th {
  background-color: #f5f7fa;
  color: #303133;
  font-weight: 600;
  text-align: left;
  padding: 10px 12px;
  border: 1px solid #ebeef5;
  white-space: nowrap;
  position: sticky;
  top: 0;
  z-index: 10;
}

.excel-style-table td {
  padding: 10px 12px;
  border: 1px solid #ebeef5;
  color: #606266;
  vertical-align: top;
}

.category-row td {
  background-color: #ecf5ff;
  font-weight: 600;
  color: #409eff;
}

.option-stats {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.inline-options {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 1px;
}

.inline-option {
  display: inline-flex;
  align-items: center;
  white-space: nowrap;
}

.option-text {
  color: #606266;
  margin-right: 5px;
}

.count-text {
  color: #e6a23c;
  font-weight: 500;
}

.percentage-text {
    color: #1890ff;
    font-weight: 500;
  margin-left: 2px;
}

.no-data {
  padding: 40px 0;
  text-align: center;
  color: #909399;
  font-size: 14px;
  background-color: #fafafa;
}
</style>

